package cn.edu.lingnan.utils;

import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeGeneralRequest;
import com.aliyun.ocr_api20210707.models.RecognizeGeneralResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;

@Component
@Slf4j
public class TextExtractorUtils {

    private final Client ocrClient;

    // 通过构造器注入OCR客户端
    public TextExtractorUtils(Client ocrClient) {
        this.ocrClient = ocrClient;
    }

    /**
     * 通用文本提取方法（自动判断文件类型）
     */
    public String extractText(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件为空");
        }

        String fileName = file.getOriginalFilename().toLowerCase();
        if (fileName.endsWith(".docx")) {
            return extractFromWord(file);
        } else if (fileName.matches(".*\\.(png|jpg|jpeg|bmp)$")) {
            return extractFromImage(file);
        } else {
            throw new IllegalArgumentException("不支持的文件类型");
        }
    }

    /**
     * 解析Word文档
     */
    public String extractFromWord(MultipartFile file) throws IOException {
        try (InputStream is = file.getInputStream()) {
            XWPFDocument document = new XWPFDocument(is);
            XWPFWordExtractor extractor = new XWPFWordExtractor(document);
            log.info("Word文档解析成功,{}", extractor.getText());
            return extractor.getText();
        }
    }

    /**
     * OCR识别图片文字
     */
    public String extractFromImage(MultipartFile file) throws IOException {
        try (InputStream is = file.getInputStream()) {
            RecognizeGeneralRequest request = new RecognizeGeneralRequest().setBody(is);
            RecognizeGeneralResponse response = ocrClient.recognizeGeneralWithOptions(request, new RuntimeOptions());

            log.info("OCR识别成功:{}", response.getBody().data);
            return response.getBody().getData();
        } catch (Exception e) {
            throw new IOException("OCR识别失败: " + e.getMessage(), e);
        }
    }
}